package main.ressik;

import android.app.AlertDialog;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;

public class AddFoodController{
	
	private FoodDb fdb;
	
	
	
	
	
	/**
	 * Constructor.  Creates a new FoodDb object and also a gets the instance of FoodListView.
	 */
	public AddFoodController(){		
		fdb = FoodDb.getInstance();
	}
	
	
	
	
	
	/**
	 * The events that occur when someone clicks the AddFood button on the main page.
	 */
	public void addFoodClick(AutoCompleteTextView food_txt, AutoCompleteTextView cal_txt, AutoCompleteTextView fat_txt, AutoCompleteTextView fiber_txt, Main main, Button addFood_btn){
		String food = food_txt.getText().toString().trim();
		String cals = cal_txt.getText().toString();
		String fat = fat_txt.getText().toString();
		String fiber = fiber_txt.getText().toString();
		if (cals.equals("")){
			cals = "0";
		}
		if (fat.equals("")){
			fat = "0";
		}
		if (fiber.equals("")){
			fiber = "0";
		}
		boolean foodExists = false;

		try{
			@SuppressWarnings("unused")
			int calsInt = Integer.parseInt(cals);
			@SuppressWarnings("unused")
			int fatInt = Integer.parseInt(fat);
			@SuppressWarnings("unused")
			int fiberInt = Integer.parseInt(fiber);
		}
		catch (Exception e){
			new AlertDialog.Builder(main).setTitle("Error:").setMessage("Please make sure that Calories, Fat, and Fiber values are whole numbers").show();
			return;
		}
		
		
		for (String f:fdb.getFoodsInDb()){
			if(f.equalsIgnoreCase(food)){
				new AlertDialog.Builder(main).setCancelable(true).setTitle("Error:").setMessage(food + " Already Added").show();
				foodExists = true;
			}
		}
		if(foodExists == false){
			fdb.addFood(food, cals, fat, fiber);
			if (addFood_btn.getText().equals("Add Food")){
				Toast.makeText(main, food + " Added", Toast.LENGTH_SHORT).show();
			}
			if (addFood_btn.getText().equals("Update Food")){
				Toast.makeText(main, food + " Updated", Toast.LENGTH_SHORT).show();
			}
		}
		food_txt.setText("");
		cal_txt.setText("");
		fat_txt.setText("");
		fiber_txt.setText("");
    }
	
	
	
	
	
	/**
	 * The events that occur when the "Update Food" button is clicked.
	 */
	public void updateFoodClick(AutoCompleteTextView food_txt, AutoCompleteTextView cal_txt, AutoCompleteTextView fat_txt, AutoCompleteTextView fiber_txt, Main main, Button addFood_btn){
		food_txt.setEnabled(true);
		String food = food_txt.getText().toString().trim();
		fdb.deleteFood(food);
		addFoodClick(food_txt, cal_txt, fat_txt, fiber_txt, main, addFood_btn);
		addFood_btn.setText("Add Food");
	}
	
	
	
}
